package com.sdw.message.action;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionSupport;
import com.sdw.message.pojo.ErrorName;
import com.sdw.message.service.UserService;
import com.sdw.message.util.JSONSender;

@ParentPackage("message")
@Controller()
@Scope("session")
public class LoginAction extends ActionSupport{

	/**
	 * 
	 */
	private static final long serialVersionUID = 5281936022117952084L;

	@Resource
	private UserService userService;
	
	private long id;
	private String userName;
	private String password;
	private String type;
	private String xh;
	private String sfzh;
	private String email;
	
	private String validateCode;
	public void setId(long id) {
		this.id = id;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public void setType(String type) {
		this.type = type;
	}


	public void setXh(String xh) {
		this.xh = xh;
	}

	public void setSfzh(String sfzh) {
		this.sfzh = sfzh;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public void setValidateCode(String validateCode) {
		this.validateCode = validateCode;
	}

	@Action(value="login")
	public void login(){
		HttpServletRequest request = ServletActionContext.getRequest();
		
		String remoteAddr = request.getRemoteAddr();
		ServletContext context =request.getSession().getServletContext();
		String serverCode = (String) context.getAttribute(remoteAddr);
		
		Map<String, Object> data = new HashMap<String, Object>();
		
		try{
			if(StringUtils.isEmpty(this.validateCode) || !this.validateCode.equalsIgnoreCase(serverCode)){
				data.put("result", ErrorName.ValidateCodeError.toString());
				data.put("message", "验证码输入有误.");
				return;
			}
			if(!this.userService.existUserName(this.userName)){
				data.put("result", ErrorName.UserNameNotExist.toString());
				data.put("message", "用户名不存在。");
				return;
			}
			
			if(!this.userService.validateUserNameAndPassword(this.userName, this.password)){
				data.put("result", ErrorName.PasswordError.toString());
				data.put("message", "用户名或者密码错误。");
				return;
			}
			
			data.put("result", ErrorName.Success.toString());
			data.put("message", "验证码输入有误！");
			return;
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			JSONSender.send(ServletActionContext.getResponse(), data);
		}
	}
}
